<!-- 字典数据 -->
<script setup lang="ts">
import {
  getDictDataPage,
  getDictFormData,
  addDict,
  updateDict,
  deleteDict,
} from "@/api/dict";

defineOptions({
  name: "dictItem",
  inheritAttrs: false,
});

const props = defineProps({
  dictId: {
    type: Number,
    default: () => {
      return "";
    },
  },
  typeName: {
    type: String,
    default: () => {
      return "";
    },
  },
});

watch(
  () => props.dictId,
  (newVal: Number) => {
    queryParams.dictId = newVal;
    formData.dictId = newVal;
    resetQuery();
  }
);

const styleList = ref([
  "default",
  "primary",
  "success",
  "info",
  "warning",
  "danger",
]);

const dataFormRef = ref(ElForm);

const loading = ref(false);
const ids = ref<number[]>([]);
const total = ref(0);

const queryParams = reactive<any>({
  pageNum: 1,
  pageSize: 10,
  dictId: props.dictId,
});

const dictList = ref<any[]>();

const dialog = reactive({
  title: "",
  visible: false,
});

const formData = reactive<any>({
  status: 1,
  dictId: props.dictId,
  sort: 1,
  isDefault: "1",
});

const rules = reactive({
  label: [{ required: true, message: "请输入字典名称", trigger: "blur" }],
  value: [{ required: true, message: "请输入字典值", trigger: "blur" }],
  isDefault: [{ required: true, message: "请选择是否默认", trigger: "blur" }],
  status: [{ required: true, message: "请选择状态", trigger: "blur" }],
});

/**
 * 查询
 */
function handleQuery() {
  if (queryParams.dictId) {
    loading.value = true;
    getDictDataPage(queryParams)
      .then(({ data }) => {
        dictList.value = data.records;
        total.value = data.total;
      })
      .finally(() => (loading.value = false));
  }
}

/**
 * 重置查询
 */
function resetQuery() {
  queryParams.pageNum = 1;
  handleQuery();
}

/**
 * 行checkbox change事件
 *
 * @param selection
 */
function handleSelectionChange(selection: any) {
  ids.value = selection.map((item: any) => item.id);
}

/**
 * 打开字典表单弹窗
 *
 * @param dictId 字典ID
 */
function openDialog(dictData?: any) {
  dialog.visible = true;
  if (dictData) {
    dialog.title = "修改字典";
    Object.assign(formData, dictData);
  } else {
    dialog.title = "新增字典";
  }
}

/**
 * 字典表单提交
 */
function handleSubmit() {
  dataFormRef.value.validate((isValid: boolean) => {
    if (isValid) {
      loading.value = false;
      const dictId = formData.id;
      if (dictId) {
        updateDict(formData)
          .then(() => {
            ElMessage.success("修改成功");
            closeDialog();
            resetQuery();
          })
          .finally(() => (loading.value = false));
      } else {
        addDict(formData)
          .then(() => {
            ElMessage.success("新增成功");
            closeDialog();
            resetQuery();
          })
          .finally(() => (loading.value = false));
      }
    }
  });
}

/**
 * 关闭弹窗
 */
function closeDialog() {
  dialog.visible = false;
  resetForm();
}

/**
 * 重置表单
 */
function resetForm() {
  dataFormRef.value.resetFields();
  dataFormRef.value.clearValidate();

  formData.id = undefined;
  formData.status = 1;
  formData.sort = 1;
  formData.typeCode = props.dictId;
}

/**
 * 删除字典
 */
function handleDelete(id?: number) {
  const dictypeIds = ref<any>([]);
  if (id) {
    dictypeIds.value.push(id);
  }
  if (ids.value.length) {
    dictypeIds.value = ids.value;
  }
  if (!dictypeIds) {
    ElMessage.warning("请勾选删除项");
    return;
  }

  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    deleteDict(dictypeIds.value).then(() => {
      ElMessage.success("删除成功");
      resetQuery();
    });
  });
}

onMounted(() => {
  handleQuery();
});
</script>

<template>
  <div class="app-container">
    <el-card shadow="never">
      <template #header>
        <el-button
          type="success"
          @click="openDialog()"
          v-hasPerm="['system:dictData:add']"
          ><i-ep-plus />新增</el-button
        >
        <el-button
          v-hasPerm="['system:dictData:delete']"
          type="danger"
          :disabled="ids.length === 0"
          @click="handleDelete()"
          ><i-ep-delete />删除</el-button
        >
      </template>

      <!-- 数据表格 -->
      <el-table
        v-loading="loading"
        :data="dictList"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="50" />
        <el-table-column label="字典名称" prop="label" align="center" />
        <el-table-column label="字典值" prop="value" align="center" />
        <el-table-column label="是否默认" align="center">
          <template #default="scope">
            <el-tag v-if="scope.row.isDefault === '1'" type="success"
              >是</el-tag
            >
            <el-tag v-else type="info">否</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="回显样式" align="center">
          <template #default="scope">
            <el-tag :type="scope.row.style" v-if="scope.row.style">{{
              scope.row.style
            }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center">
          <template #default="scope">
            <el-tag v-if="scope.row.status === 1" type="success">启用</el-tag>
            <el-tag v-else type="info">禁用</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="备注" align="center">
        </el-table-column>
        <el-table-column fixed="right" label="操作" align="center">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              link
              @click="openDialog(scope.row)"
              v-hasPerm="['system:dictData:update']"
              ><i-ep-edit />编辑</el-button
            >
            <el-button
              type="danger"
              size="small"
              link
              @click.stop="handleDelete(scope.row.id)"
              v-hasPerm="['system:dictData:delete']"
              ><i-ep-delete />删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-if="total > 0"
        v-model:total="total"
        v-model:page="queryParams.pageNo"
        v-model:limit="queryParams.pageSize"
        @pagination="handleQuery"
      />
    </el-card>

    <!-- 表单弹窗 -->
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      width="500px"
      @close="closeDialog"
    >
      <el-form
        ref="dataFormRef"
        :model="formData"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="字典类型名称">{{ typeName }}</el-form-item>
        <el-form-item label="字典标签" prop="label">
          <el-input v-model="formData.label" placeholder="请输入字典名称" />
        </el-form-item>
        <el-form-item label="字典值" prop="value">
          <el-input v-model="formData.value" placeholder="字典值" />
        </el-form-item>
        <el-form-item label="回显样式" prop="style">
          <el-select
            v-model="formData.style"
            clearable
            placeholder="回显样式"
            style="width: 140px"
          >
            <el-option
              v-for="item in styleList"
              :key="item"
              :label="item"
              :value="item"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number
            v-model="formData.sort"
            controls-position="right"
            :min="0"
          />
        </el-form-item>

        <el-form-item label="是否默认" prop="isDefault">
          <el-radio-group v-model="formData.isDefault">
            <el-radio label="是" value="1" />
            <el-radio label="否" value="0" />
          </el-radio-group>
        </el-form-item>

        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="formData.status">
            <el-radio label="正常" :value="1" />
            <el-radio label="停用" :value="0" />
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="formData.remark" type="textarea" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
